package core.scan;


import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.system.SystemUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

@Slf4j
public class ScanXmlConfig extends AbstractScanPackage {

    private static ScanXmlConfig scanXmlConfig;

    public static synchronized ScanXmlConfig newInScanXmlConfig(){
        if(scanXmlConfig == null){
            scanXmlConfig = new ScanXmlConfig();
        }
        return scanXmlConfig;
    }

    private static List<ResourceXml> resourceXmls = new LinkedList<>();

    public synchronized void scanResourceByPackage(String packageName) throws Exception {
        List<String> list = scanPackage(packageName,"xml");
        for(String filePath : list){
            ResourceXml resourceXml = new ResourceXml();
            if(SystemUtil.getOsInfo().isLinux()){
                ClassPathResource classPathResource = new ClassPathResource(filePath);
                resourceXml.setDocument(classPathResource.getStream(),null);
            }else{
                //未打包测试使用
                resourceXml.setDocument(null,new File(filePath));
            }
            resourceXml.setId(filePath.substring(filePath.lastIndexOf(File.separator) + 1));
            resourceXmls.add(resourceXml);
        }
    }

    public List<ResourceXml> getResourceXmls(){
        return this.resourceXmls;
    }

    public Object loadConfig(String configFileName,Class c) throws Exception {
        if(configFileName == null){
            throw new NullPointerException("configFileName is null");
        }
        if(!configFileName.endsWith(".xml")){
            configFileName = configFileName + ".xml";
        }
        for(ResourceXml resourceXml : resourceXmls){
            if(!resourceXml.getId().equals(configFileName)){
                continue;
            }
            return resourceXml.loadConfigBean(c);
        }
        return null;
    }

}
